//路由器是express下的功能
const express=require('express');
//创建路由器对象
const r=express.Router();
//引入连接池模块
const pool=require('../pool.js')

//往路由器中添加路由
r.post('/reg',(req,res)=>{
	let obj=req.body
		console.log(obj)
 	

if(obj.uname==''){
res.send({code:401,msg:'uname required'});
return;
}else if(obj.upwd==''){
res.send({code:402,msg:'upwd required'});
return;
}else if(obj.email==''){
res.send({code:403,msg:'email required'});
return;
}else if(obj.phone==''){
res.send({code:404,msg:'phone required'});
return;
}else{
pool.query('INSERT INTO xz_user SET ?',[obj],(err,result)=>{
if (err){throw err;}else{console.log(result)}
res.send({code:200});
})//对应pool.query
}//对应}else{
})//对应r.post('/reg',(req,res)=>{
//导出路由器对象,导出的是对象可直接用

//2.用户登录
//post  /login

r.post('/login',(req,res)=>{
//2.1获取post请求的的数据
//res.send('登陆成功')
let obj=req.body
console.log(obj)
//2.2验证数据是否为空
if (obj.uname===''){
res.send({code:401,mas:'uname required'});
return;   
}else if (obj.upwd===''){
res.send({code:402,mas:'upwd required'});
return;
}
//2.3执行SQL语句
pool.query('SELECT * FROM xz_user WHERE uname=? AND upwd=?',[obj.uname,obj.upwd],(err,result)=>{
if (err)   throw err;
console.log(result);
//如果数组长度为0，说明登录失败；否则登录成功
if(result.length===0){
  res.send({code:301,mas:'login err'})

}else{
res.send({code:200,mas:'login suc'})

}

 });
});

//3 修改用户
//get    /apdate
r.get('/update',(req,res)=>{
//3.1获取查询字符串传递的数据
let obj=req.query
console.log(obj)
let i=400
for(let key in obj){
//console.log(key,obj[key])
//判断属性值是否为空
if(obj[key]==='0'){
	i++
  res.send({code:i,msg:key+'required'});
	return;
};
};

//3.3执行SQL语句
pool.query('UPDATE xz_user SET ? WHERE uid=?',[obj,obj.uid],(err,result)=>{
  if (err)  throw err;
  console.log(result);
  //返回结果是对象，如果对象的affctedRows属性值为0说明修改失败，否则修改成功
  if(result.affectedRows===0){
   res.send({code:301,msg:'update err'});
  
  }else{
   res.send({code:200,msg:'update suc'});
  };

});
//res.send('修改成功')
});


//4.用户列表
//get  /list
r.get('/list',(req,res)=>{
   //获取字符串查询传递的数据
   let obj=req.query;
   console.log(obj)
   //如果页码为空默认为1
   if(obj.pno==='' || obj.pno<1)  obj.pno=1;
   //如果每页的数据量为空或者赋值，默认为3
   if(obj.count==='' || obj.count<1)  obj.count=3;
   //4.3将每页的数据量转为整形
   obj.count=parseInt(obj.count);
   //4.4计算开始查询的值
   let start=(obj.pno-1)*obj.coutn;
   //执行SQL语句
  pool.query('SELECT * FROM xz_user LIMIT ?,?',[start,obj.count],(err,result)=>{
if(err) throw err;
//console.log(result);
//响应给浏览器端
res.send(result);
});

   //res.send('用户列表')
   

});


r.get('/delete',(req,res)=>{
let obj=req.query
console.log(obj)
if(obj.uid===''){
res.send({code:401,msg:'uid require'})
	return;
};
//let yid=parseInt(obj.uid)
pool.query('delete from xz_user where uid=?',[obj.uid],(err,result)=>{
if (err)  throw err;
console.log(result);
//返回的是对象，如果对象下的affectedRows为0删除失败，否则删除成功
if(result.affectedRows===0){
res.send({code:301,msg:'delete err'})
}else{
res.send({code:200,msg:'delete suc'})
}
});
	

});

//导出路由对象
module.exports=r;



